use crate::types::TResult;
use image::{DynamicImage, ImageFormat};
use std::io::Cursor;
use tauri_plugin_http::reqwest::{self, StatusCode};

/// 截取远程屏幕
pub async fn screenshot(addr: String) -> TResult<DynamicImage> {
    let res = reqwest::get(addr).await?;
    match res.status() {
        StatusCode::OK => {
            let content_type = res.headers().get("Content-Type");
            let format = match content_type {
                Some(content_type) => match content_type.to_str() {
                    Ok("image/png") => ImageFormat::Png,
                    Ok("image/jpeg") | Ok("image/jpg") => ImageFormat::Jpeg,
                    _ => return Err("暂不支持的图片格式".into()),
                },
                _ => return Err("数据流未指定内容格式".into()),
            };
            let body = res.bytes().await?;
            let reader = Cursor::new(body);
            let img = image::load(reader, format)?;
            Ok(img)
        }
        _ => Err("远程截图失败".into()),
    }
}
